/*!
 * X weibo JavaScript Library v1.1
 * http://x.weibo.com/
 * 
 * Copyright 2010 SINA Inc.
 * Date: 2010/10/28 21:22:06
 */

(function(X, $){
var FALSE = false,

	TRUE = true,

    Req = X.request,
    Box = X.ui.MsgBox,
	getCfg = X.getCfg,
	getWb = X.getWb,
	doc = document,
	Util = X.util,
    getText = X.lang.getText,
	parseTpl= X.ax.Tpl.parse;

X.use('action')
/**
 * @class Xwb.mod.GlobalActionFilter
 * 全局动作拦截器
 * @static
 */
 
/**
 * @property authFilter
 * 该拦截器检测登录用户是否具备执行当前动作的权限。<br/>
 * 目前检测的权限有：
  * <ul>
 * <li>
    登录权限
   </li>
 * </ul>
    登录权限：如果当前action.na未设置为true，则提示要求用户登录。<br/>
    登录类型由全局配置loginCfg属性指定。<br/>
    登录类型：
 * <ul>
 * <li>仅使用新浪帐号直接登录</li>
 * <li>仅使用原有站点帐号登录</li>
 * <li>使用新浪帐号与原有站点帐号并存方式登录</li>
 * </ul>

 */


// 增加全局action拦截器，
// 对于要求登录的action转至登录页面
.addFilter(function( e, act){
    if(  e.get('na') || ( act && act.na ) )
	    return TRUE;
    // 未登录且未指明na属性,要求用户登录
	if ( !X.getUid() ) {
		//使用第三方登录，新浪微博t:sina,騰訊微博t:qq,人人网t:renren
        if(e.get('e') === 'lg' )
            X.mod.authLogin.open2( e.get('t') );
	    else{
			
			//处理酷炫画报页点图片评论
			if(getCfg('page') == 'youji'){
				if($('#youjiImgBox').length){
					var cmBox = X.use('youjiImg');
					cmBox.display(0);
				}
			}
			
			var loginBox = Xwb.use('loginBox'),
			    reloadUrl = e.src.href;   //记下登录成功后的跳转链接
			if( reloadUrl && new RegExp("^\/.+|http|"+location.host).test(reloadUrl) )
                loginBox.beClickedLink = e.src.href;
			loginBox.display(1);
		}
		return FALSE;
	}
}, TRUE)

/**
 * @class Xwb.mod.PageActions
 * 公共action处理
 * @static
 */
 
 /**
  * @event null
 * 对于一些根据是否登录跳转的链接,点击时,未登录则弹出登录框,登录后根据地址跳转
 */
 .reg('null', function(e){
     try{
        location.href = e.src.href;
     }catch(e){};
 })
 
/**
 * @event sd
 * 分享到微博弹
 * @param {String} [m] 弹出时微博框内容
 */
.reg('sd', function( e ){
	e.lock(1);
	var type = e.get('t'), u = e.get('u') || X.getUid(), $t = $(e.src), box = null, d = {}, lock = 0, bind = []
	, bindList = {'sina':'新浪微博', 'qq' : '腾讯微博', 'renren' : '人人网'},
    edata = e.data;
    
	box = X.use('postBox',{
		autoCenter : false,	
		title : '分享',
		btnData : null, //第三方绑定列表
		userName : $('#account').text(),
		cs : ' win-form win-form-s1 win-form-rec win-fixed',
		post:function(){
			if(lock == 1) return;
			var ch = box.jq('input[type=checkbox]:checked'),len = ch.length, target = [];
			var shareWarn = box.jq('#selectWb'), xwb_word_cal = box.jq('#xwb_word_cal');
			if(len == 0){
				box.jq('#selectWb').cssDisplay(1);
				return;
			}
			shareWarn.cssDisplay(0);
			xwb_word_cal.cssDisplay(1);
			for(var i=0;i<len;i++){
				target.push(ch[i].value)
			}
			var text = this.checkText();       
			if(!text){
				this.jqInputor.focus();
				return;
			}						
			lock = 1;
			var pic = !$('#picArea').hasClass('hidden') ? box.jq('#picArea img').attr('src') : '';
			if( pic.charAt(0) === '/'  ){
				pic = location.protocol +'//' + location.host + pic;  //带上完整路径
			}
			Req.doShare(text, target.join(','), pic, d.title, d.url, e.get('t'), u, function(rd){
				lock = 0;
				if(rd.isOk()){								
					box.close();
					Box.success('','分享成功');
				}
			});
		},
		
		bindSave : function(){
			if(bind.length)
				getShareString(bind[0], edata);
			else 
				box.jq('#bindWard').cssDisplay(1);
		},
		
		beforeShow : function(){
			box.jq('#bindWard').cssDisplay(0);
			box.jq('#shareBody').cssDisplay(0);	
			box.jq('#other').cssDisplay(0);
			box.jq('#loading').cssDisplay(1);
		    !window.XMLHttpRequest && $("#gmap select").hide(); //IE6弹出层被select档在最上面
		}, 
        beforeHide: function(){
		    !window.XMLHttpRequest && $("#gmap select").show(); //IE6弹出层被select档在最上面
			return true;
		},
		checkText : function(){
			this.jqWarn.cssDisplay(1);
			return X.mod.PostBase.checkText.call(this);			
		}
	});
	
	box.display(TRUE);
	box.jqInputor.focus(function(e){
		box.jq('#shareWarn').cssDisplay(0);
		box.jqWarn.cssDisplay(1);		
	});
	e.lock(0);
	Req.bindLst(getCfg('uid'), function(rd){		
		if(rd.isOk()){
			var data = box.btnData = rd.getData();
			if(data['sina'] || data['qq'] || data['renren']){
				//type可能是人，也可能是yj
				getShareString(data, edata);
			}else{							
				box.jq('#loading').cssDisplay(0);
				box.jq().addClass('win-bind-account');
				box.jq('#other').cssDisplay(1);
				X.use('action').reg('con',function(er){				
					var authLog = X.mod.authLogin;
					authLog.onPopupCallback = function(nickName){
						this.logWin.close();
						var t = this.type;
						if(bind.length) bind[0][t] = 1;
						else{
							bind[0] = {};
							bind[0][t] = 1;
						}
						box.jq('#'+t+'Btn').replaceWith('已绑定'+bindList[t]);
					};
					authLog.logFail = function( errcode ){
						this.logWin.close();
						Box.error("提示",Req.ERRORMAP[ errcode ] || "未知错误");
					}
					window.bind3PartSucc = Util.bind(authLog.onPopupCallback, authLog);
					window.bind3PartFail = Util.bind(authLog.logFail, authLog);
					authLog.open2( er.get('t'), 'bind' );
					
				});
			}
		}
	});
	
	function getShareString(data, edata){
        //触发事件的element带的data
        edata = edata||{};
        
	    if( type == "weibo" ){
			box.selectionHolder.setText( edata.txt || $("#inviteTxt").val() );
			box.checkText();
			d.title = "分享";
			d.url = edata.url || '';
			var src = e.get('pic');
			var picArea = box.jq('#picArea');
			picArea.append($('<div id="loadDiv" class="loading"></div>')).cssDisplay(1);					
			var img = box.jq('#picArea img')[0];
			Util.drawImage( src, 100,67,function(obj){
				picArea.find('#loadDiv').remove();
				$(img).attr('src',src).css({width:obj.width, height: obj.height});
				img.className = '';
			});					
			var ch = box.jq('input[type=checkbox]');
			var hash = { 'sina':0, 'qq':1, 'renren':2 }
			for( var a in hash ){
				data[a] ? ch.eq(hash[a]).attr('checked',true) : ch.eq(hash[a]).parent().cssDisplay(0);
			}
			box.jq().removeClass('win-bind-account');
			box.jq('#loading').cssDisplay(0);
			box.jq('#other').cssDisplay(0);
			box.jq('#shareBody').cssDisplay(1);
		    return ;
		}
		Req.getShareString(type, u, function(r){
			if(r.isOk()){
				d = r.getData();
				box.selectionHolder.setText(d.text);
				box.checkText();
				
				var src =  type=="yjsd" ? e.get('pic') : d.pic ;
				if(src){
					var picArea = box.jq('#picArea');
					picArea.append($('<div id="loadDiv" class="loading"></div>')).cssDisplay(1);					
					var img = box.jq('#picArea img')[0];
					Util.drawImage( src, 100,67,function(obj){
						picArea.find('#loadDiv').remove();
						$(img).attr('src',src).css({width:obj.width, height: obj.height});
						img.className = '';
					});					
				}
				
				var ch = box.jq('input[type=checkbox]');
				
				var hash = { 'sina':0, 'qq':1, 'renren':2 }
				for( var a in data )
					ch.eq(hash[a]).attr('checked',true);
				
				ch.each(function(i, o){
				    var $o = $(o);
					function checkState(){
						if( box.jq('input[type=checkbox]:checked').length == 0 )
							box.jq('#selectWb').cssDisplay(1);
						else box.jq('#selectWb').cssDisplay(0);
					}
					if( !$o.attr('checked') ){
						$o.click(function(e){
							var authLog = X.mod.authLogin;
							if( box.bindLock === true ){
								if( authLog.logWin ){
									if( authLog.logWin.closed ){
										box.bindLock = false;
										$o.click();
									}
									else 
										authLog.logWin.focus();
								}
								return false;
							}
							box.bindLock = true;
							authLog.onPopupCallback = function(nickName){
								Box.alert("提示","绑定成功", function(){ 
									$o.unbind();
									$o.bind('click',checkState);
									$o.attr('checked',true); 
								});
								this.logWin.close();
							};
							authLog.open2( $o.attr('value'), 'bind' );
							return false;
						});
					}
					else $o.bind('click',checkState);
				});
					
				box.jq().removeClass('win-bind-account');
				box.jq('#loading').cssDisplay(0);
				box.jq('#other').cssDisplay(0);
				box.jq('#shareBody').cssDisplay(1);
			}
		});
	}
})

.reg('liketoo', function(e){
	e.lock(1);
	var wid = e.get('y'), $t = $(e.src), 
		placeType = parseInt(e.get('t')),    //喜欢按钮所在场景
		url,param = '',
	   actionType = 0;
	   
	if( placeType == 2 )
		actionType = $t.hasClass('btn-like-done') ? 0 : 1;
    else if( placeType == 6 )
		actionType = $t.hasClass('like') ? 1 : 0;
	
	//喜欢文章	
	url = e.get('url');
	if(url){
		url = Req.jsAPI('articleApi','like_set');
		param = {id : wid, like : actionType, type:e.get('type')};
	}
	
	if( placeType == 7 ){
		Box.anchorConfirm(e.src,'确认要取消吗？',function(btn_id){
			if(btn_id === 'ok')
				reqCancelLike();
			else e.lock(0);
		});
	}
	else reqCancelLike();

	function reqCancelLike(){
		Req.youjiLike(url, param, wid, actionType , function(ret){
		   if (ret.isOk()) {
				var num = Number($('#likenum').text());
				if( actionType === 1){//喜欢完
					switch( placeType ){
						case 7:  //space.youji 喜欢的游记列表
							$t[0].className = ('liked');	
							var $span = $t.find('span')
							$span.html( +$span.html() + 1 );
							break;
						case 6:  //游记列表页
							$t[0].className = ('liked');	
							var $span = $t.find('span')
							$span.html( +$span.html() + 1 );
							break;
						case 2:   //游记详细页(博文、画报)
							$(e.src).addClass('btn-like-done');						
							if($('#picHead').length){
								var img = $('#account').parent().find('img').attr('src');
								var name = $('#account').text();
								var imgs = $('#picHead>a');
								if(imgs.length == 12) imgs.eq(11).remove();
								if(imgs.length)
									$('#picHead').prepend('<a href="/space.ta/id-'+getCfg('uid')+'" title="'+name+'"><img src="'+img+'"></a>');
								else
									$('#picHead').html(('<a href="/space.ta/id-'+getCfg('uid')+'" title="'+name+'"><img src="'+img+'"></a>'));
							}
							if(num) $('#likenum').text(++num)
							else $('#likenum').text(1);
							break;
						default : 
							break;
					}
					//$('#likePeople').html('');
				}else{//取消
					switch( placeType ){
						case 7:   //space.youji 喜欢的游记列表
							$(e.src).closest('li').remove();
						case 6:
							$t[0].className = 'like';
							var $span = $t.find('span');
							$span.html( +$span.html() - 1 );
							break;
						case 2:
							$(e.src).removeClass('btn-like-done');
							if($('#picHead').length){
								var imgs = $('#picHead>a');
								imgs.eq(0).remove();
							}
							if(num) $('#likenum').text(--num);
							break;
						default :
							break;
					}
				}
			} else {
			   Box.tip(ret.getMsg());
			}
			e.lock(0);
		});
	}
})

//喜欢
.reg('like', function(e) {
    if (!e.lock()) {
        var wid = e.get('w'),
            sid = e.get('s') || e.sid,
			type = parseInt(e.get('t')||0) ? +e.get('t') : 0,
            clsFav = type == 2 ? 'tour-like' : 'ico-like',
            clsFaved = type == 2 ? 'tour-like-done' : 'ico-liked',
            $src = $(e.src),
            $em = $src.find('em')[0] ? $src.find('em') : $src.find('b'),
            $ctlEle = $src.hasClass(clsFav) ? $src : $em,
			v = +!!$ctlEle.hasClass(clsFav),
			val = v ? 1 : -1,
			like;
        
        e.lock(1);

		//type不为0的时候读取游记id
		if(type)  wid  = e.get('y') || e.get('w');
		if(type == 0 ){
			like = Req.like;
		} else {
			like = Req.youjiLike;
		}
        like('','', wid, v ,function(ret){
           if (ret.isOk()) {
              // Box.anchorTipOk($src[0], '成功！');
				//修改wb状态
				var count, weiboPage = false;//微博详细页
				if(type == 0 ){
					if(getCfg('wbList') && getCfg('wbList')[wid]){
						var wb = getCfg('wbList')[wid];
						wb.liked = true;
						wb.likes = wb.likes ? +wb.likes :parseInt($em.text());
						count = wb.likes = (+wb.likes) + val;
					}else{
						weiboPage = true;
					}
				} else {					
					var youji = Xwb.getCfg('youji');
					if(youji){
						youji.whether_liked = true;
						
						youji.like_count = youji.like_count ? +youji.like_count :parseInt($em.text());
						count = youji.like_count = youji.like_count + val;
					}
				}
				if(v == 1){
				    e.src.title = '取消喜欢';
				}else{
					e.src.title = '添加喜欢';
				}
				//状态被改变放弃执行动画
                /*
				var keyarr = Xwb.util.parseKnV($(e.src).attr('rel'));
				if( !(type==1 && wid == keyarr.y || wid == keyarr.w ) ){
					e.lock(0);
					return ;
				}
                */
				count  = count == undefined ?  (parseInt($em.text()) + val) :count;
				
				//游记内容页面 特殊类型
				if(type !== 2 && val !=-1 ) {
					var offset = $src.offset();
					
					var img = $('<img src="/img/heart.png"/>').appendTo('body');
					img.css({
						position: 'absolute',
						width : 14,
						top : offset.top,
						left : offset.left,
						height : 14,
						'z-index':100000
					});
					img.animate({
						top :  offset.top - 14,
						left: offset.left - 6,
						width : 25,
						height:25,
						opacity: 0.4
					},400,function(){
						img.remove();
						$src
							.removeClass(v?clsFav:clsFaved)
							.addClass(v?clsFaved:clsFav);
						$em.html(count>-1?count:0);
						e.lock(0);
					});
				} else {
						
						$src
							.removeClass(v?clsFav:clsFaved)
							.addClass(v?clsFaved:clsFav);
							
						$em.html(count>-1?count:0);
						e.lock(0);
				}
				
            } else {
               Box.tip(ret.getMsg());
                e.lock(0);
            }
        });
    }
})


//抽奖页的景点列表 想去,去过
.reg('spotState', function(e){
    e.lock(1);
    var sid = e.get('id'), new_state = e.get('ns'), fid = e.get('fid');	
	Req.setFm( {'sid': sid, 'state': new_state,'fid': fid} , function(ret){
		if (ret.isOk()){
			var $src = $(e.src),
			    fid = ret.getData();
			if( new_state == 1 ){  //想去
				var $em = $src.parent().find('em'),
				    $another_a = $src.parent().prev().find('a'),
				    $another_em = $src.parent().prev().find('em');
				$src.replaceWith('<a class="goned" href="javascript:;">想去</a>');
				$em.html( +$em.html() + 1 );
				$another_a.replaceWith('<a class="gone" rel="e:spotState,id:'+sid+',fid:'+fid+',ns:2" href="#">去过</a>');
				$another_em.html( Math.max( +$another_em.html() - 1, 0) );	
			}
			else {	//去过
				var $em = $src.parent().find('em'),
				    $another_a = $src.parent().next().find('a'),
				    $another_em = $src.parent().next().find('em');
				$em.html( +$em.html() + 1 );
				$src.replaceWith('<a class="goned" href="javascript:;">去过</a>');
				$another_a.replaceWith('<a class="gone" rel="e:spotState,id:'+sid+',fid:'+fid+',ns:1" href="#">想去</a>');
				$another_em.html( Math.max(+$another_em.html() - 1, 0) );	
			}
		}
		e.lock(0);
	});	
	return false;
})

/**
 * @event fw
 * 弹出微博转发框
 * @param {String} w 微博ID
 */
.reg('fw', function( e ){
    var wbId = e.get('w')
    
        //是否正在審核
        v = e.get('v');
    
    if (v) {
		Xwb.use('verifyBox',{
			appendTo : doc.body
		}).setAnchor(e.src).display(true);
    } else {
		var con = {u:{id:1794880402},rt:'',tx:'【专家和记者有话说 】据北京市足协有关人士介绍，这支俄罗斯少年队刚获得了2011年西伯利亚联邦区冠军。“人家专业队打咱业余队，赢球很正常。”一位北京的小学生足球队教练说。据记者了解，15：0的比分被夸大了，其实是11比0。40分钟内，业余球队输给专业球队十几个球其实也正常（北京晚报）'}
	
        // 打开转发框
        var fb = Xwb.use('forwardBox');
        fb.display(true)
          .setContent(wbId, con, X.getUid())
          .selectionHolder
          .focusStart();
    }
})

/**
 * @event trd_fl
 * 关注第三方的weibo帐号, 前提是已绑定
 * @param {String} uid 关注用户ID
 * @param {Number} trdType 第三方类型类型
 */
 .reg('trd_fl', function(e){
	var data = e.data,
		uid = data.uid,
		isBinded = data.isBinded;
	if( isBinded == 0 ){
		//未登录或未绑定状态，弹新窗口进行授权：index.php?m=account.friConnect
		X.mod.authLogin.trdFllow( e.get('trdType') );
	}else {
		//已登录并绑定状态，调后端接口：index.php?m=jsApi/public.createSinaFriendship 参数：sina_uid，方式：GET
		Req.jsApiCall( 'public','createSinaFriendship', {'sina_uid': uid}, function(r){
			if( r.isOk() ){
				$(e.src).replaceWith('<span class="btn-s7 btn-s7-disabled followed"><span><i></i>已关注</span></span>');
			}else Box.alert('提示',r.getMsg());
		})
	}
	return false;
 },{na:1})


/**
 * @event fl
 * 加关注
 * @param {String} u 关注用户ID
 * @param {Number} t 动作类型
 * t值可为<br/>
  * <ul>
 * <li>1:用&lt;span class=&quot;followed-btn&quot;&gt;样式显示已关注；</li>
 * <li>2:用&lt;em&gt;显示已关注</li>
 * <li>其它为刷新当前页</li>
 * </ul>
 */
.reg('fl', function( e ){
    var uid    = e.get('u');
    var jqTrig = $(e.src);
    
    // 设置action提交标记，可有效防止重复响应
    e.lock(1);
    Req.follow(uid, 0, function( ed ){
        // #1020805，用户先前已关注，但由于缓存未更新引起，现作为关注成功处理
        if( ed.isOk() || ed.getCode() == '1020805'){
			var type = e.get('t'), $src = $(e.src);
			switch (parseInt(type)) {
    			case 1: //今日话题、他的微博
					
					var cls = e.get('cls'), cls = cls?'ico-followed' :'btn-followed';
					var ocls = e.get('cls') ?true:'';
    				$src.replaceWith('<a class="'+cls+'" rel="e:ufl,t:1,cls:'+ocls+'" href="#">' + getText('已关注') + '</a>');
					
					//$src.replaceWith('<span class="btn-s7 btn-s7-disabled followed"><span><i></i>已关注</span></span>');
    			break;
    
    			case 2: 
					$src.replaceWith('<span class="btn-s7 btn-s7-disabled followed" rel="e:ufl,t:8"><span><i></i>已关注</span></span>');
    				//$src.replaceWith('<em>' + getText('已关注') + '</em>');
    			break;
                // ta
                case 3:
                    $src.replaceWith('<div class="operated-box"><span class="followed-btn">' + getText('已关注') + '</span><em>|</em><a href="#" rel="e:ufl,t:3" class="cancel">'+ getText('取消') + '</a></div>');
                break;
				case 4:
					$(e.src).parent().find('.ico-each-followed, .ico-followed').cssDisplay(1);
					$src.replaceWith('<a href="#" class="ico-del-s2"  rel="e:ufl,t:5">取消关注</a>');
				break;
				case 5 : 
					var cls = e.get('cls'), ocls = cls?true:'';
					cls = cls? 'ico-each-followed' : 'btn-each-followed';
					$src.replaceWith('<a rel="e:ufl,t:6,cls:'+ocls+'" class="'+cls+'" href="#">互相关注</a>');
				break;
				case 7 :
					var f = e.get('f');
					if(f == undefined || f == 0 || f == 1 ){
						$src.cssDisplay(0);
						$src.parent().find('#ufl').cssDisplay(1);
					}else{
						$src.cssDisplay(0);
						$src.parent().find('#fl').cssDisplay(1);
					}					
				break;
				case 8 : 
					$src.replaceWith('<span class="btn-s7 btn-s7-disabled each-followed" rel="e:ufl,t:9"><span><i></i>相互关注</span></span>');
				break;
				case 9 :
					$src.replaceWith('<span class="ico-followed-s2">已关注</span>');
				break;
				case 10 :
					$src.replaceWith('<span class="ico-each-followed">相互关注</span>');
				break;				
				case 11 : 				
					$src.replaceWith('<a href="#" class="btn-s7 btn-s7-disabled followed" rel="e:ufl,t:11"><span><i></i>已关注</span></a>');
					break;
				case 12 : 				
					$src.replaceWith('<a href="#" class="btn-s7 btn-s7-disabled each-followed"  rel="e:ufl,t:12"><span><i></i>互相关注</span></a>');
					break;
    			default:
    				location.reload();
			}
        }else {
            if(ed.getCode() == '1020806'){
                //如果该用户一天超过500次关注行为，弹窗提示
                Box.confirm('', getText('你今天已经关注了足够多的人，先去看看他们在说些什么吧？'), function(btn){
                    if(btn == 'ok')
                        location.href = Req.mkUrl('ta', '', 'id='+uid);
                });
            }else Box.tipWarn(ed.getMsg());
        }
        e.lock(0);
    });
})

/**
 * @event ufl
 * 取消关注
 * @param {String} u 用户ID
 * @param {Number} [f] 动作类型
 * f值可为<br/>
  * <ul>
 * <li>1:显示“关注他”标签</li>
 * <li>其它为刷新当前页</li>
 * </ul>
 */
.reg('ufl', function(e) {
	Box.anchorConfirm(e.src, getText('确定要取消关注？'), function(btnId){
        if(btnId == 'ok'){
            e.lock(1);
			var uid = e.get('u');
			var act = parseInt(e.get('t'));

			Req.unfollow(uid, '', function(re) {
				if (re.isOk()){
				    switch(act){
				        case 1:
							var cls = e.get('cls'), ocls =  cls?'ico-follow' : 'btn-follow';
				            $(e.src).replaceWith('<a rel="e:fl,t:1,cls:'+cls+'" href="#" class="'+ocls+'">' + getText('加关注') + '</a>');
				        break;
						case 2 :
							$(e.src).closest('li').remove();
						break;
				        case 3:
				            $(e.src).parent().replaceWith('<a class="skin-bg addfollow-btn" rel="e:fl,t:3" href="#">' + getText('加关注') + '</a>');
				        break;
						case 5:
							$(e.src).parent().find('.ico-each-followed, .ico-followed').cssDisplay(0);
							$(e.src).replaceWith('<a href="#" class="btn-s4"  rel="e:fl,t:4"><span>' + getText('加关注') + '</span></a>');
						break;
						case 6:
							var cls = e.get('cls'), ocls = cls? 'ico-follow' : 'btn-follow';
							$(e.src).replaceWith('<a rel="e:fl,t:5,cls:'+cls+'" href="#" class="'+ocls+'">' + getText('加关注') + '</a>');
							break;
						case 7:
							$(e.src).cssDisplay(0);
							$(e.src).parent().find('#fl').cssDisplay(1);
						break;
						case 8: 
							$(e.src).replaceWith('<a href="#" class="btn-s7 btn-addfollow" rel="e:fl,t:2"><span><i>+</i>加关注</span></a>');
						break;
						case 9: 
							$(e.src).replaceWith('<a href="#" class="btn-s7 btn-addfollow" rel="e:fl,t:8"><span><i>+</i>加关注</span></a>');
						break;
						case 11 : 				
							$(e.src).replaceWith('<a href="#" class="btn-s7 btn-addfollow" rel="e:fl,t:11"><span><i>+</i>加关注</span></a>');
							break;
						case 12 : 				
							$(e.src).replaceWith('<a href="#" class="btn-s7 btn-addfollow" rel="e:fl,t:12"><span><i>+</i>加关注</span></a>');
							break;
						default:
				            window.location.reload();
				        break;
				    }
				} else {
					Box.tipWarn(re.getMsg());
				}
			    e.lock(0);
			});
		}
	});
	
})

/**
 * @event rs
 * 弹出举报对话框
 * @param {String} w 微博ID
 */
.reg('rs', function(e){
    var wbId = e.get('w');
    var wb = getWb(wbId);
    var box = Xwb.use('Box', {
    	cs:'win-report',
        contentHtml : 'SpanBoxContent',
        title:'举报不良信息',
        appendTo : document.body,
        closeable:true,
        mask:true,
        destroyOnClose : true,
        actionMgr:true,
        autoCenter:true,
        // html template data
        nick : wb.u.sn,
        img  : wb.u.p,
        text : wb.tx,
        onactiontrig:function(e){
            switch(e.data.e){
                case 'ok' :
                    var text = this.jq('#content').val();
                    Req.reportSpam(wbId, text, function(ret){
                        if(ret.isOk()){
                            Box.success('', '您的举报已提交，我们将尽快处理，感谢您对我们工作的支持！');
                        }
                        box.close();
                    });
                break;
                
                case 'cancel':
                    this.close();
                break;
            }
        }
    });
    
    box.display(true);
    box.jq('#content')
       .focus();
})
/**
 * @event blm
 * 弹出屏蔽微博对话框
 * @param {String} w 微博ID
 */
.reg('blm', function(e){
	 Box.anchorConfirm(e.src,'确定要屏蔽该微博？', function(btnId){
        if(btnId == 'ok'){
            var wbId = e.get('w');
            e.lock(1);
            Req.shieldBlog(wbId, function( r ){
                if( r.isOk() ){
                    Box.anchorTipOk(e.src, '屏蔽成功！');
                    $(e.src).replaceWith('<span>已屏蔽</span>');
                }
                e.lock(0);
            });
        }
    });
})

//刷新页面
/**
 * @event rl
 * 刷新页面
 */
.reg('rl', function(){
	location.reload();
}, {na: TRUE})

// 收藏, favourite
/**
 * @event fr
 * 弹出收藏对话框
 * @param {String} w 微博ID
 */
.reg('fr', function( e ){
    var wbId = e.get('w'),
    
        v = e.get('v');
    
    if (v) {
		Xwb.use('verifyBox',{
			appendTo : doc.body
		}).setAnchor(e.src).display(true);
    } else {
        e.lock(1);
        Req.fav(wbId, function( r ){
            if( r.isOk() ){
                Box.anchorTipOk(e.src, '收藏成功！');
                $(e.src).replaceWith('<span>已收藏</span>');
            }else {
                Box.tipWarn(r.getMsg());
            }
            e.lock(0);
        });
    }
})

/**
 * @event fr
 * 弹出取消收藏对话框
 * @param {String} w 微博ID
 * @param {Number} t 为1时当请求成功后将微博从列表移除，否则显示“收藏”按钮
 */
.reg('ufr', function(e) {
	 Box.anchorConfirm(e.src,'确定要删除该收藏？', function(btnId){
        if(btnId == 'ok'){
            e.lock(1);
			var wbId = e.get('w');
			Req.delFav(wbId, function( r ){
				if( r.isOk() ){
				    // 如果指定t的值为1，将微博从列表移除
				    if(e.data.t == 1){
				        var jq = $(e.getEl('w'));
						jq.slideUp(500, function() {
							jq.remove();
							e.lock(0);
						});
					} else {
						$(e.src).replaceWith('<a rel="e:fr" href="#">收藏</a>');
						e.lock(0);
					}
				}
			});
		}
	 })
})

/**
 * @event cm
 * 评论微博
 * @param {String} w
 */
.reg('cm', function( e ){
     var wbId = e.get('w'),
         itemEl = $( e.getEl('w') ),
         cmt = itemEl.data('xwb_cmt'),
         v = e.get('v');
     
     if (v) {
		Xwb.use('verifyBox',{
			appendTo : doc.body
		}).setAnchor(e.src).display(true);
     } else {
         if( !cmt ){
	       var wb = getWb(wbId);

           cmt =  X.use('CmtArea', {
                    wbId:wbId, 
                    wbUid    : wb && wb.u.id,
                    appendTo : itemEl.find('.feed-content'), 
                    trigEl : e.src
                  });
           itemEl.data('xwb_cmt', cmt);
         }
         
         if(! cmt.display() ){
            cmt.display(TRUE);
            cmt.load(function(){
                cmt.cmtBox.jqInputor.focus();
            });
         }else cmt.display(FALSE);
     }
})

// trun left 向左转
.reg('tl', function(e) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle) {
		var wid = e.get('w'),
			st = e.get('v');
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}

	wbEle.trun('left');
}, {na:TRUE})

// trun right 向右转
.reg('tr', function(e) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle) {
		var wid = e.get('w'),
			st = e.get('v');;
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}

	wbEle.trun('right');
}, {na:TRUE})

//还原原来的缩略图片
.reg('zo', function(e) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle) {
		var wid = e.get('w'),
			st = e.get('v');;
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}
	if($(document).scrollTop() > $wb.find('div[name="img"]').offset().top ){
		$(document).scrollTop($wb.offset().top-21);
	}
	wbEle.zoomOut();
}, {na:TRUE})

// zoom in 放大图片
.reg('zi', function( e ) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle)
	{
		var wid = e.get('w'),
			st = e.get('v');;
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}

	wbEle.zoomIn();

}, {na:TRUE})

// play video 播放视频
.reg('pv', function(e) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle)
	{
		var wid = e.get('w'),
			st = e.get('v');;
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}

	wbEle.playVideo(e);

}, {na:TRUE})

//close video
.reg('cv', function(e) {
	var $wb = $(e.getEl('w'));
	var wbEle = $wb.data('wbEle');

	if (!wbEle)
	{
		var wid = e.get('w'),
			st = e.get('v');;
		wbEle = X.use('WbElement', {$wb: $wb,psrc: e.get('p'), wid: wid, state: st, wbData: getWb(wid)});
		
		$wb.data('wbEle', wbEle);
	}

	wbEle.closeVideo(e);
}, {na:TRUE})

/**
 * @event dl
 * 弹出删除我发布的微博对话框
 * @param {String} w 微博ID
 */
.reg('dl', function( e ){
    var wbId = e.get('w'),
        v = e.get('v');
        
    Box.anchorConfirm(e.src, getText('确定删除该微博吗？'), function(btnId){
        if(btnId === 'ok'){
            e.lock(1);
            Req.del(wbId, v, function(re){
                var el = $(e.getEl('w'));
                if( re.isOk() ){
					if(el.parent().children().length>1)
						el.slideUp('normal', function(){
							el.remove();
						});
					else location.reload();
                }else Box.tipWarn(re.getMsg());
                e.lock(0);
            });
        }
    });
})


/**
 * @event rm
 * 回复短消息
 * @param {String} [u] 用户ID
 * @param {String} [n] 昵称
 */
.reg('rm', function( e ){
    X.use('myMsg').reply(
        e.get('u'), e.get('n')
    );
})


/**
 * @event dml
 * 删除短消息整个对话
 * @param {String} m 短消息ID
 */
.reg('dml', function(e){
	 Box.anchorConfirm(e.src, getText('确定要删除该短消息？'), function(btnId){
        if(btnId == 'ok'){
            e.lock(1);
            var uid = e.get('u');
            Req.delDia(uid, function(rt){
                if(rt.isOk())
                    location.reload();
				else
					Box.alert('',rt.getMsg());
                e.lock(0);
            });
        }
    });
	
})

/**
 * @event dm
 * 删除短消息
 * @param {String} m 短消息ID
 */
.reg('dm', function(e){
	 Box.anchorConfirm(e.src, getText('确定要删除该短消息？'), function(btnId){
        if(btnId == 'ok'){
            e.lock(1);
            var mid = e.get('m');
            Req.delMsg(mid, function(rt){
                if(rt.isOk())
                    location.reload();
                e.lock(0);
            });
        }
    });
	
	
})



/**
 * @event sdm
 * 发短消息
 * @param {String} [c] 内容
 * @param {String} [n] 昵称
 */
.reg('sdm', function( e ){
    var myMsg = X.use('myMsg');
    myMsg.display(TRUE)
         .reset();
    var content = e.get('c');
    if(content)
        myMsg.selectionHolder.setText(content);
    var nick = e.get('n');
    if(nick)
         myMsg.jqSender.val(nick);
    
    if(nick)
        myMsg.jqContent.focus();
    else myMsg.jqSender.focus();
})

//刷新验证码 verify code reflash
.reg('vcr', function(e){
    var vcimg = e.src
	    ,oriSrc = vcimg.src.replace(/&_=\d+/g,'');
	if( $( vcimg ).data("state") === "loading" ){
		return false;
	}
	$(vcimg).data("state", "loading");
	vcimg.onload = function(){  
		$(vcimg).data("state","loaded");
	}
	if( oriSrc.indexOf('?') > 0){
		vcimg.src = oriSrc + "&_="+(new Date().getTime());
	}else vcimg.src += '?' + "&_="+(new Date().getTime());
	return false;
})

//问答部分
//感谢
.reg('ty',function(e){
	var aid  = e.get('aid');
	Req.thankYou({aid:aid}, function(r){
		if(r.isOk()){
			Box.anchorTipOk(e.src, '感谢成功！',function(){
				var span = $(e.src).find('span');
				span.text(parseInt(span.text())+1);
			});
		}else{
			Box.alert( '提示' ,r.getError());
		}
	});
})
//有帮助
.reg('auf',function(e){
	var aid  = e.get('aid');
	Req.ansUseful({aid:aid}, function(r){
		if(r.isOk()){
			Box.anchorTipOk(e.src, '成功！',function(){
				var span = $(e.src).find('span');
				span.text(parseInt(span.text())+1);
			});
		}else{
			Box.alert( '提示' ,r.getError());
		}
	});
})
//无帮助
.reg('ans',function(e){
	var aid  = e.get('aid');
	Req.ansNouse({aid:aid}, function(r){
		if(r.isOk()){
			Box.anchorTipOk(e.src, '成功！',function(){
				var span = $(e.src).find('span');
				span.text(parseInt(span.text())+1);
			});
		}else{
			Box.alert( r.getError() );
		}
	});
})

//第三方绑定
.reg('con', function(e){
    var authLog = X.mod.authLogin,
	    t = e.get('t');
	authLog.onPopupCallback = function(nickName){
		this.logWin.close();
		switch(e.get('s')){
			case 'youjiWb': Box.alert("提示","绑定成功");break;
			case 'youjiAl':location.reload();break;
			default: 
			    $(e.src).closest('div').html( parseTpl('btnUnBind',{ 'nickName': nickName, 't': t }) );
		}
	};
	authLog.logFail = function( errcode ){
		this.logWin.close();
		if( errcode == '417407' )   //提示:第三方帐号已绑定
		    Box.alert("提示",Req.ERRORMAP[ errcode ] );
	    else Box.error("提示",Req.ERRORMAP[ errcode ] || "未知错误");
	}
	window.bind3PartSucc = Util.bind(authLog.onPopupCallback, authLog);
	window.bind3PartFail = Util.bind(authLog.logFail, authLog);
	authLog.open2( t, 'bind' );
})
//第三方解除绑定
.reg('unCon', function(e){
    var t = e.get('t');
	if( e.get('uniquelg') == 1 )  // 如果以第三方帐号登录,且没有绑定其他第三方帐号
	    return Box.alert("提示","抱歉，您无法取消创建帐号时使用的第三方帐号的绑定。");
	Req.unBind3Part(t, function(ae){
	    if(ae.isOk()){
		    $(e.src).closest('div').html(X.ax.Tpl.parse('btnBind',{'t': t}));
		}else Box.error('提示',ae.getError());
	});
})

//邮箱验证
.reg('ckEmail', function(e){
    var mail = $("input[name=email]").val();
	if(!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(mail)){
	    $("#mailTip").removeClass('hidden');
		return ;
	}
	function getEmailSuffix(mailSuff){
		if('sina.com,sina.com.cn,vip.sina.com.cn,sina.cn,163.com,qq.com,126.com,hotmail.com,sohu.com,yahoo.cn,yahoo.com,yahoo.com.hk,139.com,wo.com.cn,189.cn,3g.sina.cn'.indexOf(mailSuff) != -1) 
		    return 'http://mail.'+mailSuff;
		else return '';
	};
	Req.ckEmail(mail, function(e){
	    if(e.isOk()){
		    var emailUrl = getEmailSuffix(mail.substring(mail.indexOf('@')+1));
			if(emailUrl == ''){
			    emailUrl = mail;
			}else emailUrl = '<a href="' + emailUrl+'" target="blank">'+ mail + '</a>'
		    var mes = '验证邮件已发送，请前往'+ emailUrl +'查看，并确认邮件';
		 	Box.alert('提示',mes, function(){ location.reload(1); });
		}
		else Box.error('绑定失败',e.getError());
	})
})
//景点导航页 spots.nav
.reg('chProv', function(e){
    var pid = e.get('prov_id');
    X.use( 'provSelect', { prov_id: pid } ).display(1).anchor( e.src, 'bl' );
})

//经验分享-不回答
.reg('expdl', function(e){
	e.lock(1);
    var id = e.get('id'), $el = e.jq('id');
	Req.expDelete(id, function(r){
		if(r.isOk()){
			if(getCfg('page') == 'experience.consult'){
				if(e.jq('tid').find('dd').length == 1){
					e.jq('tid').remove();
				}else{
				var target = e.jq('e').parent().parent();
				target.prev().remove();
				target.remove();
				}
				return;
			}
			$el.prev().remove();
			$el.remove();
		}else{
			Box.alert('提示',r.getMsg());
			e.lock(0);
		}
		
	})
})

//经验分享-编辑提交
.reg('expes', function(e){
	e.lock(1);
	var id = e.get('id'), $el = $(e.getEl('id')), $txa = $el.find('textarea'), text = $txa.val(), df = e.get('df'), l = Util.byteLen(text);
	if(/^\s*$/.test(text) || l < 10){
		Box.tip('不能少于5个汉字');
		e.lock(0);
	}else{
		$txa.removeClass('style-focus');
		$el.find('.btn-s4').addClass('btn-s4-disabled');
		Req.expEditSubmit(id, text, function(r){
			if(r.isOk()){
				$el.find('.msg-cont').children().remove();
				$el.find('.msg-cont').html('<p><span>'
				+ '</span><a href="#" rel="e:expe">[编辑]</a></p>');
				$el.find('.msg-cont p span').text(text);
				X.ax.ActionMgr.setRel(e.jq('id'), 'v', text);
				if(getCfg('page') == 'experience.myExp'){
					var $newEl = $el.find('.msg-cont');
					//$el.find('p').html($el.find('p span').html());
					$newEl.find('a').remove();
					$newEl.append($('<span class="time">' + e.get('t') + '</span><span class="operate"><a href="#" rel="e:expe">编辑</a></span>'));
					$newEl.wrapInner('<div class="answer"></div>')
				}
				
			}else{
				$txa.addClass('style-focus');
				$el.find('.btn-s4').removeClass('btn-s4-disabled');
				Box.alert('提示',r.getMsg());
			}
			e.lock(0);
		})
	}	
})	


//经验分享-编辑问题
.reg('expe', function(e){
	var df = e.get('df'), html, $el = e.jq('id').find('.msg-cont'), oldText = $el.find('p span').text();
	html = ['<textarea class="t2 style-normal style-focus">' + oldText + '</textarea>',
	'<span class="submit-area">',
		'<a href="#" class="btn-s1 btn-s1-gray" rel="e:expcc"><span>取消</span></a><a href="#" class="btn-s1" rel="e:expes"><span>确定</span></a>',
	'</span>'].join('');
	$el.html(html);
	$el.data('v', oldText);
	if(getCfg('page') == 'experience.myExp'){
		$el.append($('<span class="time">' + e.get('t') + '</span>'));
		$el.find('textarea').attr('class', 't3 style-normal style-focus');
	}
})

//经验分享-取消编辑
.reg('expcc', function( e ){
	var $el = e.jq('id').find('.msg-cont'), text = $el.data('v');
    $el.children().remove();
	$el.html('<p><span>'
	+ '</span><a href="#" rel="e:expe">[编辑]</a></p>');
	$el.find('p span').text(text);
	if(getCfg('page') == 'experience.myExp'){
		$el.find('a').remove();
		$el.append($('<span class="time">'+ e.get('t') +'</span><span class="operate"><a href="#" rel="e:expe">编辑</a></span>'));
		$el.wrapInner('<div class="answer"></div>')
		
	}
})


//移除足迹
.reg('delMark', function(e){
	var id = e.get('i');
	Box.confirm('', getText('确定要移除足迹吗?'), function(btn){
		if(btn == 'ok'){
			Req.delMark({sid:id}, function(r){
				if(r.isOk()){
					//Box.anchorTipOk(e.src,'移除成功',function(){
						$(e.src).closest('li').remove();
					//});
				}else{
					Box.error('',r.getMsg());
				}
			});
		}
	});
})

//勋章浮层
.reg('medal',function(e){
   var p = {uid: e.get('uid'), flag: e.get('flag')}
   X.use('Dlg',{
        cs : 'win-fixed win-medal',
    	appendTo : "body",
    	dlgContentHtml : '<div class="loading"></div>',
    	title: '领取勋章',
		closeable : true,
		destroyOnClose : true,
		param : p,
		onViewReady : function(){
		    var tthis = this;
		    Req.postReq(Req.mkUrl('jsApi/public','getMedalDetail'), this.param, function(r){
			    if(r.isOk()){
				    var d = r.getData(),
					    info = $.extend(d.info,{state: d.state});
					tthis.setTitle(info.name);

				    tthis.jq('#xwb_dlg_ct').html(parseTpl('medal', info));
					if( p.flag == 'invite' ){
						var str = '活动时间：2011-12-15至2012-01-14<br/>'
								   +'<a href="'+Req.mkUrl('events/invite','getfans')+'">立即参加活动</a>';
						tthis.jq('#xwb_dlg_ct div.info p:last').html( str )
					}
				}else {
				    tthis.close(1);
				    Box.error('',r.getError());
				}
			})
		}
   }).display(1);
})
//游记详细页显示图片评论
.reg('imgcm',function(e){
    //过滤冒泡的事件
    if ( e.get('e') != 'imgcm' ) return;
    var t = e.get('t'), param = {hasCmt : true}, src = '', $src = $(e.src);
	if(t == 'pic'){
		param = {hasCmt : false, srcList:X.getCfg('srcList')};	
		src = $src.parent().attr('_rel');
	}
	var box = X.use('youjiImg', param);
    
    //兼容旧的格式
	var $img = $src.find('img');
    src = src || $src[0].src || ($img[0] && $img[0].src) || e.get('url');
	
	var pidurl = src.split('/'), len = pidurl.length, pid = pidurl[len-1].split('_web_pic')[0];
	box.pid = pid;
	box.reply(src,e.get('w'));
	box.setOffset();
	
	e.get('focus') == '1' && box.cmtBox.jqInputor.focus();
	
	if( X.getCfg('view_type') === "preview" ){
	    box.jq('#cmtBox').cssDisplay(0); // 预览不显示评论框
	}
},{na:true})

.reg('Ydel',function(e){
	var yid = e.get('yid');
	Box.confirm('提示','你确认要删除这条游记吗？',function(id){
		if(id=='ok'){
			e.lock(1);
			Req.postReq(Req.jsAPI('youjiApi','delYouji'),{id:yid},function(r){
				if(r.isOk()){
					location.href= Req.mkUrl('space','youji');
				} else {
					Box.error('提示',r.getMsg());
				}
			});
		}
	})
})
/**
 * @event sd
 * 游记图片分享到发布微博
 * @param {String} [m] 弹出时微博框内容
 */
.reg('yjsd', function( e ){
    var box = X.use('postBox');
    var text = "分享微博内容";
		
    box.display(TRUE)
       .reset();
	   
	box.uploadPic = e.get('url');
    box.selectionHolder.setText(text||'');
    if(text)
        box.checkText();
})

//我想去
.reg('wt', function(e){
	var id = e.get('i')||e.get('sid');
/* 	Req.setFm({sid:id, state:1},function(r){
		if(r.isOk()){
			Box.anchorTipOk(e.src,'添加成功',function(){
				if(e.get('t') == 2){					
					$(e.src).closest('li').unbind();					
					$(e.src).closest('.operate').html('<span><a class="btn-s9" href="#"><span><i class="ico-succeed">成功添加到我的足迹！</i></span></a></span>');
				}
			});
		} else {
			Box.error('提示',r.getMsg());
		}
	}); */
	
	Req.addWantTo(id, function(r){
		if(r.isOk()){
			Box.anchorTipOk(e.src,'添加成功',function(){
				if(e.get('t') == 2){					
					$(e.src).closest('li').unbind();					
					$(e.src).closest('.operate').html('<span><a class="btn-s9" href="#"><span><i class="ico-succeed">成功添加到我的足迹！</i></span></a></span>');
				}
			});
		}
	});
})

//我去过
.reg('gt', function(e){
	var id = e.get('i'), status = 1;
	if(!id){
		id = e.get('sid');
		status = 0;
	}
	
	Req.addJourney('','','','','',id, 0,'',status, function(r){
		if(r.isOk()){
			var t = e.get('t');
			if(t == 2){					
				$(e.src).closest('li').unbind();
				$(e.src).closest('.operate').html('<span><a class="btn-s9" href="#"><span><i class="ico-succeed">成功添加到我的足迹！</i></span></a></span>');
			}else if(t == 1){
				$(e.src).replaceWith('<span class="btn-s7 btn-s7-disabled"><span><i class="ico-followed">去过啦</i></span></span>');
			}
		} else {
			Box.error('提示',r.getMsg());
		}
	})	
})
.reg('rq',function(e){
	var cmt = X.cfg.cmt;
	var url = e.get('url').replace('_original_pic','_thumbnail_pic');
	cmt.cmtBox._param.data.imgUrl = url;
	Util.focusEnd( cmt.cmtBox.jqInputor.val("回复@"+ $.trim($("div.tour-title-s1 div.desc a").html()) +" 图片: ")[0] );
})

//esg: edit spot guide; 路书编辑 纠错
.reg('esg', function( e ){
    var ptype = e.get('guide_id'),
	    paragraph = $(e.src).parent('span').next().text();
    X.use('editGuide', $.extend( e.data, { title: e.src.innerHTML, paragraph : paragraph, spots_id : e.get('sid') })).display(1);
})

//显示评论框
.reg('scm', function(e){

    X.use('CommentBox')
	.display(1)
    .setParams({
        wid: e.get('y') ? e.get('y') : e.get('w'),
        src : e.src,
		data : e.get('y') ? { wid : e.get('w') }:{}
    });

})


//附近的景点
.reg('near', function(e){
    var spots = X.getCfg('spots');
    
    if (!spots) return;
	var $t = $(e.src), inst = $t.data('near');
		
    if (!inst) {
		X.use('LoadGoogleMap').initUI({}, '','',function(){
			inst = X.use('NearMap', {
				cfg : spots,
				clickObj : $t
			});
			$t.data('near', inst);
			inst.display(1);
		});

    }else{
		inst.display(1);
	}
    
    
}, {na: TRUE})

//设置景点状态：去过，想去等
.reg('state', function(e){

    if (e.lock()) return;
    
    e.lock(1);
    var s = parseInt(e.get('s')),
        wid = e.get('w'),
        $view = $(e.getEl('w')),
		fid = e.get('fid'),
        oper_html = '<span rel="w:'+wid+'"><a href="#" class="btn-s3" rel="e:state,s:1"><span>想去</span></a><a href="#" class="btn-s3" rel="e:state,s:2"><span>去过</span></a></span>';
    
    function changeState(param_s, action, callback) {
		var _s = param_s.state;
        action(param_s, function(r){
            var html;
            if (s == -1) {
                html = oper_html;
            } else {
                html = '<span rel="w:'+wid+',state:'+_s+',fid:'+r.getData()+'"><span class="hold">我' + (_s == 1 ? '想去': '去过') + '这里</span><a href="#" rel="e:state">修改</a>  <a href="#" rel="e:state,s:-1">删除</a></span>';
            }
            
            $view.replaceWith(html);
            
            callback && callback(r);
        });
    };
    
	var action = Util.bind(Req.setFm, Req);
    switch (s) {
		case -1: //清除
			action = Util.bind(Req.delMark, Req);
				Box.anchorConfirm(e.src,'确认要删除吗?',function(id){
					if(id=='ok'){
						changeState({sid : wid, state : s}, action, function(r){
							e.lock(0);
						});
					}else{
						e.lock(0);
					}
				})	
			break;
		case 1: //想去
		case 2: //去过
			changeState({sid : wid, state : s}, action, function(r){
				e.lock(0);
			});
			break;
        
    default:
        //$view.replaceWith(oper_html);
        var old_state = e.get('state');

        var statebox = X.use('StateBox')
            .setRadio(old_state)
            .setOkHandler(function(val){
                if (val != old_state) {
                    changeState({sid : wid, state : val, fid:e.get("fid")}, Util.bind(Req.setFm, Req));
                }
            })
            .display(1);
            
        statebox.afterHide = function(){
            e && e.lock(0);
            X.ui.Box.prototype.afterHide.call(this);
        }
    }
})
.reg('xrep',function(e){
	var t = e.get('t'),
		id ;
	switch(t){
		case 'y':
			id = e.get('yid');
			break;
		case 'c':
			id = e.get('c');
			break;
		case 'a':
			id = e.get('aid');
			break;
		case 'q':
			id = e.get('id');
			break;		
		case 'topic':
			id = e.get('c') || e.data.id;
			var tt = e.data.tt;	//tt: topicType 举报类型。可选值topic或者topic_comment
			if( !tt ) return ;
			Req.topicReport(id, tt, function(r){
				if(r.isOk()){
					if( r.getData() == -1 ){
						Box.alert('提示','存在相同举报.');
					}
					else Box.success('提示','举报成功');
				} else {
					Box.alert('提示',r.getMsg());
				}
			})
			return false;			
	}
	X.use('Report',{
		appendTo : $('body'),
		sendData : function(data){
			var self = this;
			this.Report(t)(id,data.type,data.content,function(r){
				if(r.isOk()){
					self.close();
					Box.success('提示','信息已收集!');
				} else {
					Box.alert('提示',r.getMsg());
				}
			})
		}
	}).display(1);
})

//删除通知
.reg('dn', function(e){
	var wid = e.get('w');
	if(!wid) return;
	e.lock(1);
	Box.anchorConfirm(e.src,'确认要删除吗?',function(id){
		if(id=='ok'){
			Req.delNotice(wid, function(r){
				if(r.isOk()){
					$(e.src).closest('li').remove();
				}else{
					Box.alert('提示',r.getMsg());
				}
				e.lock(0);
			});
		}else
			e.lock(0);
	})	
		
})
//change visitor or change hot spots 
.reg('ch', function(e){
    e.lock(1);
    var f = (e.get('t') === 'visitor' ? Req.getVisitor : Req.getHotSpots),
	    elm = e.src;
    f(function( r ){
	    if( r.isOk() ){
		    $(elm).closest("div.mod").replaceWith( $(r.getData()) );
		}else Box.alert('提示',r.getMsg());
		e.lock(0);
	})
})

//赞成
.reg('uforns', function(e){
	var st = e.get('st'), t = e.get('t'), c = e.get('c');
	if(t == st) return; //当前状态已选中
	e.lock(1);
	Req.setUseful(c, t, function(r){	
		e.lock(0);
		if(r.isOk()){			
			var $e = $(e.src), $s = $e.find('em'), num = Number($s.text());
			X.ax.ActionMgr.setRel($e.closest('li'), 'st', t);
			if(t == 1){//赞成
				$e.replaceWith('<span class="ico-agree">赞成('+(num + 1)+')</span>');
			}else{
				$e.replaceWith('<span class="ico-oppose">反对('+(num + 1)+')</span>');
			}
		}else{
			Box.tipError(r.getMsg());
		}
	});
})

.reg('joinGroup',function(e){  //加入小组
	e.lock(1);
	var t = e.data.t, id = e.data.id, name = e.data.n;
	Req.jsApiCall('groupApi','join_group',{gid: id}, function(rst){
		if(rst.isOk()){
			switch(t){
				case '1':    //开通码头页
					$(e.src).replaceWith('<a rel="e:exitGroup,t:1,id:'+id+'" class="btn-joined" href="#">已加入</a>');
					var $gcount = $('#groupCount');
					$gcount.html( +$gcount.html()+1 );
					X.fire('setSubmitBtnState');
					break;
				case '2':		//添加小组浮层
					var liItem = parseTpl('groupItem2',{
							name : name,
							groupUrl : Req.mkUrl('group','',{id: id}),
							imgSrc : $(e.src).parent('div').prev('div.pic').find('img').attr('src')
						}
					);
					$('li.nav-group ul.subnav').append( liItem );
					$(e.src).replaceWith('<span rel="e:exitGroup,t:2,id:'+id+',n:'+name+'" class="btn-s7 btn-s7-disabled" href="#"><span>已加入</span></span>');
					break;
				case '3':		//小组首页 , 小组话题页右上侧的退出小组
					$(e.src).addClass('hidden').next('a.quit').removeClass('hidden')
					var liItem = parseTpl('groupItem2',{
							name : name,
							groupUrl : Req.mkUrl('group','',{id: id}),
							imgSrc : $('div.group-info>div.bd>a.pic>img')[0].src
						}
					);
					$('li.nav-group ul.subnav').append( liItem );
					break;
			}
			X.fire('countJoinedGroup',1);
		}
		e.lock(0);
	},'POST')
})
.reg('exitGroup',function(e){
	e.lock(1);
    Box.anchorConfirm(e.src, '确定要退出该小组吗？', function(btn){
        if (btn != 'ok') {
            e.lock(0);
            return;
        }
	    var id = e.data.id, t = e.data.t;
	    Req.jsApiCall('groupApi','group_exit',{gid: id}, function(rst){
		    if(rst.isOk()){
			    switch(t){
					case '1':
						var $gcount = $('#groupCount');
						$gcount.html( Math.max( +$gcount.html()-1,0 ) );
						$(e.src).replaceWith('<a class="btn-join" rel="e:joinGroup,t:1,id:'+id+'" href="#">加入小组</a>');
						X.fire('setSubmitBtnState');
						break;
					case '2': //添加小组浮层
						var name = e.data.n;
						$(e.src).replaceWith('<a class="btn-s7" href="#" rel="e:joinGroup,t:2,id:'+id+',n:'+name+'"><span>加入小组</span></a>');
						var $asideLis = $('li.nav-group>ul.subnav>li');
						for(var i=0;i<$asideLis.length;i++){
							var $name_link = $asideLis.eq(i).children('a');
							if( $name_link.html() == name ){
								$asideLis.eq(i).remove();
								break;
							}
						}
						break;
					case '3':    //小组首页 , 小组话题页右上侧的退出小组
					    location.reload(true);
					    break;
			    }
				X.fire('countJoinedGroup',-1);
		    }
		    e.lock(0);
	    },'POST');
    })
})
//set Topic State
.reg('sts',function(e){
	e.lock(1);
	var paramName = e.data.pn,   // paramName = 'is_hot' || 'is_good' || 'is_top'
	    state = e.data.state, // 0 取消， 1 设置
		id = e.data.id
		parms = {id: id};
	parms[paramName] =  state;
	Req.jsApiCall('groupApi','topic_setStatus',parms, function(rst){
		if(rst.isOk()){
			var paramNameHash = { is_hot: '热推', is_good: '精华', is_top: '置顶' };
			if( state == 1 )
				$(e.src).replaceWith( '<a rel="e:sts,id:'+id+',pn:'+paramName+',state:0" href="#">[取消'+paramNameHash[paramName]+']</a>' );
			else 
				$(e.src).replaceWith( '<a rel="e:sts,id:'+id+',pn:'+paramName+',state:1" href="#">['+paramNameHash[paramName]+']</a>' );
		}
		e.lock(0);
	},'POST')
})
// delete topic one 删除单张帖子  ,  单独用于帖子详细页的 删除帖子
.reg('deltOne', function(e){
	var id = e.data.id, gid = e.data.gid;
	Box.anchorConfirm(e.src, '确定要删除吗？', function(btn){
		if (btn != 'ok'){
			this.close();
			return false;
		}
		Req.topicDel( id, function(r){
			if(r.isOk())
				location.href = Req.mkUrl('group','',{id: gid});
			else Box.alert('',r.getMsg());
		})
	})
})
// group content manage 小组内容管理
.reg('gcm',function(e){
	var apiN = e.data.apiN,  		//api number, jsApi方法的索引
		id = e.get('id') || e.data.id,  //id可以是多个,以逗号分割,返回的数据会有所不同
		ids = [];
	if( e.data.isBatch ){    //是否批量
		$('div.content-list input:checked').each(function(i,item){
			ids.push( parseInt($(item).val()) );
		});
		if( !ids.length ) 
			return false;
	}else ids.push(id);
	
	var apiNameHash = {
		'1': 'topic_delete',    	//删除帖子
		'2': 'admin_reportAccept',	//接受举报包括 通过并屏蔽 和 通过并删除 两个操作
		'3': 'topic_restore',		//恢复帖子
		'4': 'admin_reportIgnore'	//忽略帖子举报
	}
	var parmas = {'id': ids.join(',')};
	switch( apiN ){
		case 1:
			break;
		case 2 :
			parmas['action'] = e.data.act_t; //接受举报对应的操作 1 通过并删除 2 通过并屏蔽
			break;
		case 3:
			break;
		case 4:
			break;
	}
	Req.jsApiCall('groupApi', apiNameHash[apiN] , parmas ,function(r){
		if(r.isOk()){
			var data = r.getData();
			if(data.result != 1){  //0 全部成功；1 全部失败；2 部分成功
				var failArr = data.fail;
				for(var i = 0;i<ids.length;i++)
					if( Util.arrayIndexOf(failArr, ids[i]) == -1 ){
						$('#id_'+ids[i]).remove();
					}
			}else Box.alert('提示','操作失败');
		}else Box.alert('',r.getMsg());
	},'POST')
})
//明信片喜欢
.reg('mlk', function(e){
	var pid = e.get('pid'), jq = $(e.src)
	, type = e.get('t'); //类型决定页面样式
	if(type == 2){
		var cls = 'btn-like', ucls = 'btn-like-done';//已喜欢
	}else{
		var cls = 'ico-like-s2', ucls = 'ico-liked';//已喜欢
	}
	e.lock(1);
	if(!jq.hasClass(ucls))
		Req.postCardLike(pid, function(r){
			e.lock(0);
			if(r.isOk()){
				//jq[0].className = cls;
				if(type == 2){
					jq.addClass(ucls);
				}else{
					var num = Number(jq.text().replace('(','').replace(')',''));
					jq.text('('+(++num)+')');
						var offset = jq.offset();					
						var img = $('<img src="/img/heart.png"/>').appendTo('body');
						img.css({
							position: 'absolute',
							width : 14,
							top : offset.top,
							left : offset.left,
							height : 14,
							'z-index':100000
						});
						img.animate({
							top :  offset.top - 14,
							left: offset.left - 6,
							width : 25,
							height:25,
							opacity: 0.4
						},400,function(){
							img.remove();
							jq
								.removeClass(cls)
								.addClass(ucls);
							e.lock(0);
						});		
				}		
			}else{
				Box.alert('',r.getMsg());
			}		
		})		
	else//取消
		Req.postCardunLike(pid, function(r){
			e.lock(0);
			if(r.isOk()){
				if(type == 2){
					jq.removeClass(ucls);
				}else{
					jq[0].className = cls;
					var num = Number(jq.text().replace('(','').replace(')',''));
					num = num == 0?0:--num;
					jq.text('('+num+')');
				}				
			}else{
				Box.alert('',r.getMsg());
			}		
		})		

})

//明信片删除(type: 1我的明信片，type :2收到的明信片)
.reg('mdel', function(e){
	var pid = e.get('pid'), jq = $(e.src), type = e.get('type'), url = e.get('url');
	Box.anchorConfirm(e.src,'确认要删除该明信片吗？',function(id){
		if(id=='ok'){
			e.lock(1);
			Req.postCardDel(pid, type, function(r){
				e.lock(0);
				if(r.isOk()){
					if(url)
						window.location = url;
					else
						jq.closest('div.item').animate( { height: 0 } , 300 ,function(){
							$(this).remove();
						});		
				}else{
					Box.alert('',r.getMsg());
				}		
			})	
		}
	})
})
//添加印象浮层
.reg('aim', function(e){
	var img_id = e.get('id'),
		aimCtrl;
	if( X.getCfg('page') === 'youji' ){
		var url = e.data.imgurl,
			sarr = url.split('/');
		img_id = sarr[sarr.length-1].split('_web_pic')[0];
		aimCtrl = X.use('addImpress',{
			addSucced: function( param, resObj ){  //override method
				$('#action_'+img_id+' a:eq(0)').replaceWith('<div class="btn-common">印象已添加</div>');
				Box.tipOk('添加印象成功.');
				
				//插入一条品论
				var comment = resObj.raw.rst.comment;
				for(var i in comment){
					comment = comment[i];    //comment只有一项,覆盖自身
				}
				var ndate = new Date(comment.create_time*1000);
				var addsAttr = {
					"wid" : 0,
					"cid" : 0,
					"create_at" : ndate.getFullYear()+'-'+(ndate.getMonth()+1)+'-'+ndate.getDay()+' '+ ndate.toLocaleTimeString(),
					"nick" : comment.user.nickname,
					"uid" : X.getUid(),
					"profileImg" : X.getCfg('face_m'),
					"level" : comment.user.level
				}
				resObj.raw.rst.comment = $.extend(comment, addsAttr);
				var r = new Xwb.request.DefaultResponseDefinition( resObj.raw );
				Xwb.fire('Cmt.afterSend',r);
			}
		})
	}
	else aimCtrl = X.use('addImpress');

	aimCtrl.setData( img_id, e.get('yjid') ).show(e.src);
})


.reg('share',function(e){
	var t = e.data.t;  // trdType
	var tn =  X.mod.trdShare.type2name[t];  //第三方名称 sina ,qq ,renren
	
	var relData = e.data;  //action data
	relData.imgUrl = $(e.src).closest('div.img-wrap').attr('src');
	
	if( !X.bindList ){
		Req.bindLst(X.getCfg('uid'), function(rd){
			if(rd.isOk())
				X.bindList = rd.getData();   //已绑定列表
			else
				X.bindList = {};
		},{async: false});   //非异步
	}
	
	//未登录 or 已登录但未绑定
	if( !X.getUid() || ( X.getUid() &&  X.bindList[tn] === undefined) ){
		var url = X.mod.trdShare.makeShareUrlByTrdType(t, relData);
		if( t == 1 || t == 2 ){
			url = url.replace(/title=([^&]*)/,function(s1){  //sina qq 会自动生成短连,去掉title后面的链接,因为会自动生成一个链接
				return s1.replace(/http.*$/,'（分享自@自游网旅游攻略）');
			});
		}

		e.src.href = url;   //修改url地址,在新页打开页面

		e.clear();  //清除
		
		e.preventDefault(false);
	}
	//已登录且绑定
	else{
		// if( X.bindList[tn] === undefined ){ 		//未绑定
			// var authLog = X.mod.authLogin;
			
			// authLog.onPopupCallback = function(nickName){
				// this.logWin.close();
				// X.bindList[tn] = true;   //记下已绑定
				// Box.success("提示",'绑定成功',function(){
					// $(e.src).click();   //再次触发事件
				// });
			// };
			// authLog.logFail = function( errcode ){
				// this.logWin.close();
				// Box.error("提示",Req.ERRORMAP[ errcode ] || "未知错误");
			// }
			// window.bind3PartSucc = Util.bind(authLog.onPopupCallback, authLog);
			// window.bind3PartFail = Util.bind(authLog.logFail, authLog);
								
			// if( authLog.logWin ){
				// if( authLog.logWin.closed )
					// authLog.open2( tn, 'bind' );
				// else 
					// authLog.logWin.focus();
			// }else 
				// authLog.open2( tn, 'bind' );
		// }
		// else{ //已绑定过

		// }
		Xwb.use('shareBox').display(true).setType(t).fillContent(t, relData);
		return false; 
	}
})

})(Xwb, $);